<template>
  <u-popup v-model="show" mode="right">
    <view class="popup-box">
      <canvas class="canvas" canvas-id="firstCanvas1" id="firstCanvas1" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd"></canvas>
      <div class="header">
        <view>
          <u-icon name="arrow-up" @click="$emit('input', false)"></u-icon>
        </view>
        <view class="title">
          签字板
        </view>
        <view class="submit" @click="submit">
          确定
        </view>
      </div>
    </view>
  </u-popup>
</template>

<script>
let context1 = null
export default {
  name: 'b-signature',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  data() {
    return {
      canvasData: []
    }
  },
  watch: {
    canvasData() {
      if (!this.canvasData.length) {
        return
      }
      context1.moveTo(this.canvasData[0].x, this.canvasData[0].y)

      for (let i = 0; i < this.canvasData.length; i++) {
        context1.lineTo(this.canvasData[i].x, this.canvasData[i].y)
      }
      context1.stroke()
      context1.draw(true)
    }
  },
  created() {
    context1 = uni.createCanvasContext('firstCanvas1', this)
    context1.setLineWidth(1)
    context1.setStrokeStyle('#000000')
  },
  methods: {
    handleTouchStart(e) {
      this.canvasData = []
      const a = e.changedTouches[0]
      this.canvasData.push({
        x: a.x,
        y: a.y
      })
    },
    handleTouchMove(e) {
      const a = e.changedTouches[0]
      this.canvasData.push({
        x: a.x,
        y: a.y
      })
    },
    handleTouchEnd(e) {
      const a = e.changedTouches[0]
      this.canvasData.push({
        x: a.x,
        y: a.y
      })
      this.$emit('canvasDataChange', this.canvasData)
    },
    canvasToImage() {
      uni.canvasToTempFilePath({
        canvasId: 'firstCanvas1',
        fileType: 'jpg',
        x: 0,
        y: 0,
        destWidth: 240,
        destheight: 60,
        success: (res) => {
          console.log(res.tempFilePath)
          let imgPath = res.tempFilePath
        },
        fail: (error) => {
          console.log(error)
        }
      })
    },
    submit() {
      this.canvasToImage()
    }
  }
}
</script>

<style lang="scss" scoped>
.popup-box {
  width: 100vw;
  height: 100vh;
  display: flex;
}
.header {
  padding: 100rpx 20rpx;
  width: 60rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  .title {
    width: 3em;
    font-weight: bold;
    font-size: 30rpx;
    transform: rotate(90deg) translateX(-50%);
  }
  .submit {
    width: 2em;
    font-size: 28rpx;
    transform: rotate(90deg) translateX(-50%);
    color: #068cf4;
  }
}
.canvas {
  width: calc(100vw - 100rpx);
  height: 100vh;
}
</style>
